from wtforms import (StringField, Form, ValidationError,
                     IntegerField, FileField)
from flask_wtf.file import FileAllowed, FileSize
from wtforms.validators import Length, Email, EqualTo, InputRequired
from models.auth import UserModel
from exts import cache
from flask import request


class BaseForm(Form):
    @property
    def messages(self):
        message_list = []
        if self.errors:
            for error in self.errors.values():
                message_list.extend(error)
        return message_list


class RegisterForm(BaseForm):
    email = StringField(validators=[Email(message="请输入正确的邮箱!")])
    email_captcha = StringField(validators=[Length(min=6, max=6, message="请输入正确邮箱格式!")])
    username = StringField(validators=[Length(min=3, max=20, message="请输入正确长度用户名!")])
    password = StringField(validators=[Length(min=3, max=20, message="请输入正确长度密码!")])
    repeat_password = StringField(validators=[EqualTo("password", message="两次密码不一致!")])
    graph_captcha = StringField(validators=[Length(min=4, max=4, message="请输入正确图形验证码!")])

    def validate_email(self, field):
        email = field.data
        user = UserModel.query.filter_by(email=email).first()
        if user:
            raise ValidationError("该邮箱已被注册!")

    def validate_email_captcha(self, field):
        email = self.email.data
        email_captcha = field.data

        cache_capcha = cache.get(email)
        if not cache_capcha or email_captcha != cache_capcha:
            raise ValidationError("邮箱验证码错误!")

    def validate_graph_captcha(self, field):
        graph_captcha = field.data
        key = request.cookies.get("_graph_captcha_key")
        cache_capcha = cache.get(key)
        if not cache_capcha or graph_captcha != cache_capcha:
            raise ValidationError("图形验证码错误!")


class LoginForm(BaseForm):
    email = StringField(validators=[Email(message="请输入正确的邮箱!")])
    password = StringField(validators=[Length(min=3, max=20, message="请输入正确长度密码!")])
    remember = IntegerField()


class UploadImageForm(BaseForm):
    image = FileField(validators=[FileAllowed(['jpg', 'png', 'jpeg'], message="请上传图片文件!"),
                                  FileSize(max_size=5 * 1024 * 1024, message="图片大小不能超过5M!")])


class EditProfileForm(BaseForm):
    signature = StringField(validators=[Length(max=100, message="个性签名不能超过100个字符!")])


class PublicPostForm(BaseForm):
    title = StringField(validators=[Length(min=3, max=200, message="帖子标题必须在3-200之间！")])
    content = StringField(validators=[InputRequired(message="请输内容!")])
    board_id = IntegerField(validators=[InputRequired(message="请输板块ID!")])


# 评论表单
class PublicCommentForm(BaseForm):
    content = StringField(validators=[InputRequired(message="请输内容!")])
    post_id = IntegerField(validators=[InputRequired(message="请输帖子ID!")])
